﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Newtonsoft.Json;
using NLog;
using System;
using System.Configuration;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;

namespace IOA.MES.HealthCheck
{
    partial class Service1 : ServiceBase
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            logger.Info("开启健康检查...");
            new TaskFactory().StartNew(() =>
            {
                var error = false;
                while (true)
                {
                    error = false;
                    try
                    {
                        var responseStr = new HttpHelper().PostJson($"{ConfigurationManager.AppSettings["apiRoot"]}/api/Auth/Ping", new { });
                        var response = JsonConvert.DeserializeObject<ResultJson<string>>(responseStr);
                        if (response.ErrCode == 200)
                        {
                            logger.Info("健康检查通过");
                        }
                        else
                        {
                            error = true;
                            ExcuteFatal(null, response.ErrMsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        error = true;
                        ExcuteFatal(ex, "");
                    }
                    var sleep = error ? 60000 : 2000;
                    Thread.Sleep(sleep);
                }
            });
        }

        private static void ExcuteFatal(Exception ex, string errMsg)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(errMsg))
                {
                    errMsg = $"服务异常：{errMsg}";
                    logger.Fatal(errMsg);
                }
                if (ex != null)
                {
                    errMsg = $"服务访问异常";
                    logger.Fatal(ex, $"服务访问异常");
                }

                var smsRequest = new SendSmsRequest
                {
                    PhoneNumbers = ConfigurationManager.AppSettings["phones"].ToString(),
                    SignName = "诣星智能",
                    TemplateCode = "SMS_16740717",
                    TemplateParam = JsonConvert.SerializeObject(new { System = "VinaMes", Module = errMsg })
                };
                var profile = DefaultProfile.GetProfile("cn-shanghai", "LTAI5tRGwHCj95n5CfZVG214", "OSwLqem1I3IqorFdVr0Tm67WoZYoHF");
                var smsResponse = new DefaultAcsClient(profile).GetAcsResponse(smsRequest);
                if (!string.Equals(smsResponse.Code, "OK", StringComparison.CurrentCultureIgnoreCase))
                {
                    logger.Fatal($"短信发送失败：{smsResponse.Message}");
                }
            }
            catch (Exception ex1)
            {
                logger.Fatal(ex1, $"短信发送失败：{ex.Message}");
            }
        }

        protected override void OnStop()
        {
            logger.Info("健康检查关闭");
        }
    }
}
